<?php
namespace app\helpers;
class MyHelper  {

    const DESC = 'DESC'; // 降序
    const ASC = 'ASC'; // 升序

    public static function getOrder() {
        return [
            self::DESC => ['msg' => '降序', 'class' => 'warning'],
            self::ASC => ['msg' => '升序', 'class' => 'success'],
        ];
    }

    public static function secondsToHour($seconds){
       if(intval($seconds) < 60)
            $tt ="00:00:".sprintf("%02d",intval($seconds%60));
       if(intval($seconds) >=60){
            $h =sprintf("%02d",intval($seconds/60));
            $s =sprintf("%02d",intval($seconds%60));
            if($s == 60){
                $s = sprintf("%02d",0);
                ++$h;
            }
            $t = "00";
           if($h == 60){
                $h = sprintf("%02d",0);
                ++$t;
           }
           if($t){
                $t  = sprintf("%02d",$t);
           }
           $tt= $t.":".$h.":".$s;
        }
        if(intval($seconds)>=60*60){
           $t= sprintf("%02d",intval($seconds/3600));
           $h =sprintf("%02d",intval($seconds/60)-$t*60);
           $s =sprintf("%02d",intval($seconds%60));
          if($s == 60){
             $s = sprintf("%02d",0);
             ++$h;
           }
           if($h == 60){
                $h = sprintf("%02d",0);
                ++$t;
           }
           if($t){
                $t  = sprintf("%02d",$t);
           }
           $tt= $t.":".$h.":".$s;
        }
        return  $seconds>0?$tt:'00:00:00';
    }

    //格式化错误输出
    public static function formatErrors($errors, $messageArr) {
      if (empty($errors)) {
        return '';
      }
        
      $outputStr = '';
      foreach ($errors as $key => $value) {
        foreach ($value as $k => $v) {
          $outputStr .= $messageArr[$key].'：'.$v;
        }
        $outputStr .= '。';
      }
      return $outputStr;
    }

    /**
     * 获取缓存key和过期时间
     *
     * @access public
     * @param  $key         配置文件中cache的key
     * @param  $params1     参数1
     * @param  $params2     参数2
     * ...
     * @return array        [key_name, expire_second]
     */
    public static function getCacheKey() {
        $options    = func_get_args();
        $paramsKey  = $options[0];
        $cacheArr   = \Yii::$app->params['CACHE_KEY'][$paramsKey];
        $options[0] = $cacheArr[0];
        $key        = call_user_func_array('sprintf', $options);
        return [$key, $cacheArr[1]];
    }

     /**
     * 日志记录函数
     * 2017年6月2日 上午11:15:10
     * @author liyee
     * @param unknown $channel
     * @param unknown $action
     * @param unknown $data
     */
    public static function inlog($channel, $action, $data){
        $data = is_string($data)?$data:json_encode($data, JSON_UNESCAPED_UNICODE);
      
        if (YII_DEBUG){
            try {
                file_put_contents(\Yii::$app->getRuntimePath().'/log'.date('Ymd').'.log', date('c').'::'.$channel.'::'.$action.'::'.$data."\n", FILE_APPEND);
            } catch (Exception $e) {
            }
        }
    }

    //post方式传输json
    public static function http_post_json($url, $jsonStr)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonStr));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        //         'Content-Type: application/json; charset=utf-8',
        //         'Content-Length: ' . strlen($jsonStr)
        //     )
        // );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // $errors = curl_error($ch);
        $err_code_arr = require(__DIR__ . "/curl_errno_array.php");
        $error_msg = $err_code_arr[curl_errno($ch)];

        curl_close($ch);
        self::inlog('myhelper', 'http_post_json', ['code'=>$httpCode,'content'=>$response, 'errors' => $error_msg, 'json_str' => $jsonStr]);
        return array($httpCode, $response);
    }

    /**
     * 求两个日期之间相差的天数
     * (针对1970年1月1日之后，求之前可以采用泰勒公式)
     * @param string $day1
     * @param string $day2
     * @return number
     */
    public static function diffBetweenTwoDays ($day1, $day2)
    {
      $second1 = strtotime($day1);
      $second2 = strtotime($day2);
        
      if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
      }
      return ($second1 - $second2) / 86400 + 1;
    }

     /**
     2  * 方法二: 获取指定日期段内每一天的日期
     3  * @date 2017-02-23 14:50:29
     4  *
     5  * @param $start
     6  * @param $end
     7  *
     8  * @return array
     9  */
    public static function getDateRange2($start, $end) {
        $range = [];
     
         for ($i = 0; strtotime($end . '-' . $i . ' days') >= strtotime($start); $i++) {
             $time = strtotime($end . '-' . $i . ' days');
             $range[] = date('Y-m-d', $time);
         }
     
         return $range;
    }

     //post方式传输json
    /**
     * 发送HTTP请求方法
     * @param  string $url    请求URL
     * @param  array  $params 请求参数
     * @param  string $method 请求方法GET/POST
     * @return array  $data   响应数据
     */
    static function http($url, $params, $method = 'GET', $header = array(), $multi = false, $duration=30) {
        $opts = array(
            CURLOPT_TIMEOUT => $duration,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_FOLLOWLOCATION => 1
        );

        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                exit('不支持的请求方式！');
        }

        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        self::inlog('myhelper', 'http', ['parames' =>$params, 'url' => $url ,'data'=>$data]);

        return $data;
    }


    //解析json数据
    public static function decode_respanse_data(){
        
    }


}
